cat('Creating Table A31\n\n')

load('TableA31_data.csv')
dat = read.csv('TableA32Figure8_6_data.csv')


moransmat = matrix(ncol = 1, nrow =4)

hispcenters = coordinates(hshapes)
knn = knearneigh(hispcenters,3)
prec.knn = knn2nb(knn)
moranres =  moran.test(hshapes$pct_obama,nb2listw(prec.knn,style="W"),na.action=na.exclude,zero.policy=T)
moransmat[1:2,1] = moranres$estimate[1:2]
moransmat[3,1] = moranres$p.value
moransmat[4,1] = nrow(hispcenters)
rownames(moransmat) = c("Moran's I", "Alternative", "p", "N")

outmtable = xtable(moransmat, digits = 4)
print(outmtable,file='TableA31.tex')


cat('Creating Table 32\n\n')
distance.regression = lm(pct_obama ~ log_distance + log_median_income+pct_hisp_immigrant+pct_college,data = dat,
                         weights = total_ballots_cast)

outtable = apsrtable(distance.regression,
                     Sweave = T,
                     stars = 'default',
                     coef.names = c('Intercept', 'log(Distance)', 'log(Median Income)',  'Percent Immigrant', 'Percent College Educated'),
                     notes = '')
writeLines(
  outtable, 'TableA32.tex')


cat('Creating Figure 8.6 \n\n')
z.out = zelig(pct_obama ~ log_distance + log_median_income+pct_hisp_immigrant+pct_college,data = dat,model = 'ls',
                weights = dat$total_ballots_cast)
dists = seq(from = min(dat$log_distance),to = max(dat$log_distance), by = .001)
resmat = matrix(ncol = 6, nrow = length(dists))
for(i in 1:length(dists)){ 
    x.out = setx(z.out,log_distance = dists[i])
    s.out = sim(z.out, x.out)
    my.ev = s.out$getqi(qi='ev')
    resmat[i,1] = mean(my.ev)
    resmat[i,2:3] = quantile(my.ev,c(.05,.95))
    }
resmat[,4] = (exp(dists)/5280)/.6 #in ft, so convert to km 

plot.data = as.data.frame(resmat)

out.plot = ggplot(plot.data, aes(V4,V1)) + 
  geom_smooth(color = 'black', aes(alpha = .75)) +
  geom_ribbon(aes(ymin = V2, ymax = V3), alpha = .05) +
  theme(legend.position="none") +
  labs(x = 'Distance from nearest Black precinct (km)', y = 'Probability of voting for Obama') + 
  theme(
    plot.background = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    axis.text=element_text(size=7.5),
    axis.title=element_text(size=10)
  ) 
ggsave('Figure8_6.jpeg',plot = out.plot,
       dpi = 1200,
       width = 4.66,
       height = 4.66) 

